<?php


namespace App\Console\Commands\Tasks;

use App\Exceptions\BasicException;
use App\Models\MainDB\UserRecharge;
use App\Repositories\LogRepository;
use App\Services\Business\BusinessConfigService;
use App\Services\Tools\WxPayXCXService;
use Illuminate\Console\Command;
class XcxOrderQueryCommand extends Command
{
    protected $signature = 'task:xcx_order_query';
    protected $description = '检查是否支付成功';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $time = time();
        $time_start = $time - 180;
        $time_end = $time - 60;
        // 支付在 前 一分钟和 3分钟前 进行查询未支付的订单
        $data = UserRecharge::query()->where('add_time','>=',$time_start)->where('add_time','<=',$time_end)
            ->where('status',1)
            ->whereIn('type',[20,21])->get()->toArray();
        if(!empty($data)){
            foreach ($data as $val){
                // 获取商户
                $businessConfigService = new BusinessConfigService();
                $businessConfig = $businessConfigService->getById($val['business_config_id']);
                if ($businessConfig === null || empty($businessConfig->params)) {
                    // 记录一下
                    continue;
//                    throw new BasicException(-1, '未获取到商户配置');
                }
//                {
//                    "code": 0,
//                    "data": {
//                        "amount": "100",
//                        "body": "{\"business_id\":83}",
//                        "currency": "CNY",
//                        "mchNo": "M1730874723",
//                        "mchOrderNo": "20241114772918622973",
//                        "payOrderId": "P1856995872647921665",
//                        "state": 0,
//                        "storeId": "8465",
//                        "subject": "\u5343\u7fbd\u7a7a\u95f4",
//                        "wayCode": "OTHER"
//                    },
//                    "sign": "CB148B5952835AE6489CCD7A4C96A0EB"
//                }
                // 成功的
//                {
//                    "code": 0,
//                    "data": {
//                        "amount": "100",
//                        "body": "{\"business_id\":83}",
//                        "channelUser": "2088412640120501",
//                        "currency": "CNY",
//                        "mchFeeAmount": "1",
//                        "mchNo": "M1730874723",
//                        "mchOrderNo": "20241115495771875716",
//                        "officOrderNo": "2024111522001420501404877856",
//                        "outTransactionId": "YLZFB24111567533296",
//                        "payOrderId": "P1857299059319283714",
//                        "state": 2,
//                        "storeId": "8465",
//                        "subject": "\u5343\u7fbd\u7a7a\u95f4",
//                        "successTime": "1731649606000",
//                        "wayCode": "ALI_JSAPI"
//                    },
//                    "sign": "81B7F821564D929E1D9CEA343AA30453"
//                }
                $str = (new WxPayXCXService())->OrderQuery($val['order_sn'],$val['store_no'], $businessConfig->params);
                $logRtx = new LogRepository("user_order_sn_check");
                $logRtx->log("fanhuiinfo:", json_encode($str, JSON_UNESCAPED_UNICODE));
                $logRtx->File();
                if($str['state'] === 2 && isset($str['successTime']) && isset($str['outTransactionId'])){
                // 支付成功 进行 上锁
                try {
                    $limitKey = 'lk:callback:' . $val['order_sn'];
                    $res = app('redis')->set($limitKey, 1, 'ex', 5, 'nx');
                    if (!$res) {
                        $logRtx = new LogRepository("juhehui-pay");
                        $logRtx->log(":", "上一个正在处理");
                        $logRtx->File();
                        continue;
                    }
                    $transaction_id = $str['outTransactionId']; //微信支付订单号
                    $time_end = intval($str['successTime'] / 1000);//支付完成时间
                    $fee = $str['amount'] * 0.01;
                    $total_fee = number_format((float)$fee, 2, '.', '');
                    $notifyNext = app('repo_payment')->notifyNext($val['order_sn'], $transaction_id, $time_end, 1, $total_fee, $time_end);
                    if (!$notifyNext) {
                        throw new BasicException(-1, '操作频繁');
                    }
                    app('redis')->del($limitKey);
                } catch (\Throwable $e) {
                    $logRtx = new LogRepository("juhehui-pay");
                    $logRtx->log("err::", $e->getMessage());
                    $logRtx->File();
                    continue;
                }
                }
            }
        }
    }
}
